﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FrienDev.Data;
using FrienDev.SystemApps;

namespace FrienDev.BusinessRules
{
    public class ActivityRules
    {
        public static ActivityRules Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new ActivityRules();
                }
                return _instance;
            }
        }
        /// <summary>
        /// 判断当前用户是否为活动的创建者
        /// </summary>
        /// <param name="activityID"></param>
        /// <returns></returns>
        public bool IsCurrentUserIsActivityPromoter(int activityID)
        {
            IEnumerable<ActivitiesMember> ams = from am in _dataContext.ActivitiesMembers
                                                where am.ActivityId == activityID && am.UserId == UserRules.Instance.GetCurrentUserId() && am.ActivitiesMemberType == "promoter"
                                                select am;
            ActivitiesMember activityMember = ams.SingleOrDefault();
            if (activityMember == null)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 判断用户是否为活动的创建者
        /// </summary>
        /// <param name="activityID"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool IsActivityPromoter(int activityID, string userId)
        {
            IEnumerable<ActivitiesMember> ams = from am in _dataContext.ActivitiesMembers
                                                where am.ActivityId == activityID && am.UserId == userId && am.ActivitiesMemberType == "promoter"
                                                select am;
            ActivitiesMember activityMember = ams.SingleOrDefault();
            if (activityMember == null)
            {
                return false;
            }
            return true;
        }

        public void SendAcceptMessage(int activityId, string userId)
        {
            Activity activity = GetActivityInfo(activityId);
            string[] param = { activity.ActivityId.ToString(), activity.ActivityName };
            ApiHelper.Instance.SendSystemMessage("Activity", "Accept", userId, param);
        }

        public void SendRejectMessage(int activityId, string userId)
        {
            Activity activity = GetActivityInfo(activityId);
            string[] param = { activity.ActivityId.ToString(), activity.ActivityName };
            ApiHelper.Instance.SendSystemMessage("Activity", "Reject", userId, param);
        }

        public void SendMemberAddRequest(int activityId, string userId)
        {
            Activity activity = GetActivityInfo(activityId);
            User user = UserRules.Instance.GetUserByUserId(userId);
            string[] param = { activity.ActivityId.ToString(), activity.ActivityName,userId,user.FullName};
            ApiHelper.Instance.SendSystemMessage("Activity", "MemberAddRequest", GetActivityOrganizerId(activityId), param);
        }

        public void SendFeedbackNotice(int activityId)
        {
            List<User> users = GetActivityJoined(activityId, 0).ToList<User>();
            Activity activity = GetActivityInfo(activityId);
            string[] param = { activity.ActivityId.ToString(), activity.ActivityName, "~/Activity/ActivityFeedBackFill.aspx?activityId=" + activityId };
            foreach (User u in users)
            {
                ApiHelper.Instance.SendSystemMessage("Activity", "FeedBackNotice", u.UserId, param);
            }
        }

        public bool IsActivityNeedPermit(int activityId)
        {
            IEnumerable<Activity> activities = from a in _dataContext.Activities
                                               where a.ActivityId == activityId && a.IsNeedPermission == true
                                               select a;
            Activity activity = activities.SingleOrDefault();
            return (activity == null) ? false : true;
        }

        public object GetActivityMemberListDetail(int activityId, bool isGetCandidate)
        {
            var l = from am in _dataContext.ActivitiesMembers
                    where am.ActivityId == activityId && (am.ActivitiesMemberType == (isGetCandidate ? "candidate" : "joined") || am.ActivitiesMemberType == (isGetCandidate ? "" : "promoter"))
                    select new
                    {
                        imageUrl = ApiHelper.Instance.GetUserLogoUrl(am.UserId),
                        userNameUrl = ApiHelper.Instance.GetUserHomepageLink(am.UserId),
                        userName = am.User.FullName,
                        age = DateTime.Now.Year - am.User.Birthday.Value.Year,
                        professor = am.User.UsersDetail.Dictionary.ObjectValue,
                        contect = am.User.UsersContact.Phone,
                        userId = am.UserId,
                        activityId = am.ActivityId
                    };
            return l;
        }

        public IEnumerable<User> GetActivityCandidate(int activityID, int amount)
        {
            IEnumerable<User> user = from am in _dataContext.ActivitiesMembers
                                     where am.ActivityId == activityID && am.ActivitiesMemberType == "candidate"
                                     select am.User;
            if (user.Count() == 0)
                return null;
            if (amount != -1)
            {
                return user.Take(amount);
            }
            return user;
        }

        /// <summary>
        /// 获得活动参加者列表
        /// </summary>
        /// <param name="activityID"></param>
        /// <param name="amount">获取数量，-1为不限制数量</param>
        /// <returns></returns>
        public IEnumerable<User> GetActivityJoined(int activityID, int amount)
        {
            IEnumerable<User> user = from am in _dataContext.ActivitiesMembers
                                     where am.ActivityId == activityID && (am.ActivitiesMemberType == "joined" || am.ActivitiesMemberType == "promoter")
                                     select am.User;
            if (user.Count() == 0)
                return null;
            if (amount != -1)
            {
                return user.Take(amount);
            }
            return user;
        }

        /// <summary>
        /// 更新自定义反馈问题
        /// </summary>
        /// <param name="activityId"></param>
        /// <param name="questionList"></param>
        public void UpdateCustomFeedBackQuestion(int activityId, string questionList)
        {
            IEnumerable<Activity> activities = from a in _dataContext.Activities
                                               where a.ActivityId == activityId
                                               select a;
            Activity activity = activities.SingleOrDefault();
            if (activity == null)
                return;
            activity.CustomFeedbackQuestion = questionList;
            _dataContext.SubmitChanges();
        }

        /// <summary>
        /// 更新自定义反馈问题答案
        /// </summary>
        /// <param name="activityId"></param>
        /// <param name="userId"></param>
        /// <param name="customAnswer"></param>
        /// <param name="mark"></param>
        public void UpdateFeedBackAnswer(int activityId, string userId, string customAnswer, int[] mark)
        {
            IEnumerable<ActivitiesMember> activityMembers = from am in _dataContext.ActivitiesMembers
                                                            where am.ActivityId == activityId && am.UserId == userId
                                                            select am;
            ActivitiesMember activityMember = activityMembers.SingleOrDefault();
            if (activityMember == null)
                return;
            activityMember.OverallSatisfactionMark = mark[0];
            activityMember.ContentSatisfactionMark = mark[1];
            activityMember.OrganizeSatisfactionMark = mark[2];
            activityMember.CustomFeedbackAnswer = customAnswer;
            _dataContext.SubmitChanges();
        }


        public List<int[]> GetUsersFeedBackMark(int activityId, List<string> userIds)
        {
            IEnumerable<ActivitiesMember> activityMembers;
            List<int[]> questionMarks = new List<int[]>();
            foreach (string userId in userIds)
            {
                activityMembers = from am in _dataContext.ActivitiesMembers
                                  where am.ActivityId == activityId && am.UserId == userId
                                  select am;
                if (activityMembers.Count() == 0)
                    continue;
                ActivitiesMember activityMember = activityMembers.SingleOrDefault();
                if (activityMember.OverallSatisfactionMark == null || activityMember.ContentSatisfactionMark == null || activityMember.OrganizeSatisfactionMark == null)
                    continue;
                int[] mark = { Convert.ToInt32(activityMember.OverallSatisfactionMark), Convert.ToInt32(activityMember.ContentSatisfactionMark), Convert.ToInt32(activityMember.OrganizeSatisfactionMark) };
                questionMarks.Add(mark);
            }
            return questionMarks;
        }

        public Dictionary<string, List<string>> GetUsersCustomFeedBackAnswer(int activityId, List<string> userIds)
        {
            IEnumerable<ActivitiesMember> activityMembers;
            Dictionary<string, string> customAnswerList = new Dictionary<string, string>();
            foreach (string userId in userIds)
            {
                activityMembers = from am in _dataContext.ActivitiesMembers
                                  where am.ActivityId == activityId && am.UserId == userId
                                  select am;
                if (activityMembers.Count() == 0)
                    continue;
                ActivitiesMember activityMember = activityMembers.SingleOrDefault();
                if (string.IsNullOrEmpty(activityMember.CustomFeedbackAnswer))
                    continue;
                customAnswerList.Add(activityMember.User.FullName, activityMember.CustomFeedbackAnswer);
            }
            return GetCustomFeedBackAnswerList(customAnswerList);
        }

        /// <summary>
        /// 返回自定义反馈问题列表
        /// </summary>
        /// <param name="activityId"></param>
        /// <returns></returns>
        public List<string> GetCustomFeedBackQuestions(int activityId)
        {
            Activity activity = GetActivityInfo(activityId);
            List<string> qList = GetCustomFeedBackQuestionList(activity.CustomFeedbackQuestion);
            return qList;
        }

        public object GetUserRecentActivities(string userID)
        {
            var activities = from a in _dataContext.ActivitiesMembers
                             where a.UserId == userID && a.Activity.EndDateTime >= DateTime.Now orderby a.Activity.BeginDateTime descending
                             select new
                             {
                                 activityId = a.ActivityId,
                                 activityName = a.Activity.ActivityName,
                                 activityUrl = GetAcitivityUrl(a.ActivityId),
                                 activityDate = GetShortDate(a.Activity.BeginDateTime),
                                 beginDateTime = GetLongDateTime(a.Activity.BeginDateTime),
                                 signUpLimit = GetActivityPeopleLimit(a.ActivityId, a.Activity.SignUpLimit),
                                 activityState = GetStateDescription(GetActivityState(a.ActivityId)),
                                 postsCount = GetAcitivityPostsCount(a.ActivityId),
                                 founder = GetActivityOrganizer(a.ActivityId),
                                 founderUrl = ApiHelper.Instance.GetUserHomepageLink(GetActivityOrganizerId(a.ActivityId)),
                                 currentClub = a.Activity.Club.ClubName,
                                 friendName = a.User.FullName,
                                 clubUrl = GetClubUrl(a.Activity.ClubId)
                             };
            return activities;
        }


        //TODO:FIX
        public void SignUpActivity(string userId, int activityId, int femaleNum, int maleNum)
        {
            IEnumerable<ActivitiesMember> activitymembers = from am in _dataContext.ActivitiesMembers
                                                            where am.UserId == userId && am.ActivityId == activityId
                                                            select am;
            ActivitiesMember activityMember = activitymembers.SingleOrDefault();
            if (activityMember != null)
            {
                return;
            }
            ActivitiesMember newActivityMember = new ActivitiesMember
            {
                ActivityId = activityId,
                ActivitiesMemberType = IsActivityNeedPermit(activityId) ? "candidate" : "joined",
                UserId = userId,
                JoinDateTime = DateTime.Now,
                SingleUserSignUpFemaleNum = femaleNum,
                SingleUserSignUpMaleNum = maleNum
            };
            _dataContext.ActivitiesMembers.InsertOnSubmit(newActivityMember);
            if (!ActivityRules.Instance.GetActivityInfo(activityId).IsNeedPermission)
            {
                AddActivitySignUpTrack(activityId, ActivityRules.Instance.GetActivityInfo(activityId).ActivityName, userId);
            }
            _dataContext.SubmitChanges();

        }

        public void QuitActivity(string userId, int activityId)
        {
            IEnumerable<ActivitiesMember> activitymembers = from am in _dataContext.ActivitiesMembers
                                                            where am.UserId == userId && am.ActivityId == activityId
                                                            select am;
            ActivitiesMember activityMember = activitymembers.SingleOrDefault();
            if (activityMember == null)
                return;
            _dataContext.ActivitiesMembers.DeleteOnSubmit(activityMember);
            //FIX ME:当数据库方法提出时，应由以下方法访问数据库方法
            AddActivityQuitTrack(activityId, activityMember.Activity.ActivityName, userId);

            _dataContext.SubmitChanges();

        }

        public void InsertActivityPromoter(int activityId, string userId)
        {
            ActivitiesMember am = new ActivitiesMember
            {
                ActivityId = activityId,
                UserId = userId,
                ActivitiesMemberType = "promoter",
                JoinDateTime = DateTime.Now,
                SingleUserSignUpFemaleNum = 0,
                SingleUserSignUpMaleNum = 0
            };
            _dataContext.ActivitiesMembers.InsertOnSubmit(am);
            _dataContext.SubmitChanges();
        }

        public void AddActivityAddTrack(int activityId, string activityName)
        {
            ApiHelper.Instance.AppendTodayTrack(UserRules.Instance.GetCurrentUserId(), typeof(ActivityApplication), 0, new string[] { activityId.ToString(), activityName });
        }

        public void AddActivitySignUpTrack(int activityId, string activityName, string userId)
        {
            ApiHelper.Instance.AppendTodayTrack(userId, typeof(ActivityApplication), 1, new string[] { activityId.ToString(), activityName });
        }

        public void AddActivityQuitTrack(int activityId, string activityName, string userId)
        {
            ApiHelper.Instance.AppendTodayTrack(userId, typeof(ActivityApplication), 2, new string[] { activityId.ToString(), activityName });
        }



        /// <summary>
        /// 更新用户的活动状态
        /// </summary>
        /// <param name="activityId"></param>
        /// <param name="userId"></param>
        /// <param name="state"></param>
        public void UpdateUserActivityState(int activityId, string userId, string state)
        {
            IEnumerable<ActivitiesMember> activitymembers = from am in _dataContext.ActivitiesMembers
                                                            where am.UserId == userId && am.ActivityId == activityId
                                                            select am;
            ActivitiesMember activityMember = activitymembers.SingleOrDefault();
            if (activityMember == null)
                return;
            activityMember.ActivitiesMemberType = state;
            if (state == "joined")
            {
                AddActivitySignUpTrack(activityId, activityMember.Activity.ActivityName, userId);
            }
            _dataContext.SubmitChanges();

            //FIX ME:当数据库方法提出时，应由以下方法访问数据库方法

        }

        /// <summary>
        /// 获取用户的过期活动
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public object GetUserOldActivites(string userID)
        {
            var activities = from a in _dataContext.ActivitiesMembers
                             where a.UserId == userID && a.Activity.EndDateTime <= DateTime.Now orderby a.Activity.BeginDateTime descending
                             select new
                             {
                                 activityId = a.ActivityId,
                                 activityName = a.Activity.ActivityName,
                                 activityUrl = GetAcitivityUrl(a.ActivityId),
                                 activityDate = GetShortDate(a.Activity.BeginDateTime),
                                 beginDateTime = GetLongDateTime(a.Activity.BeginDateTime),
                                 signUpLimit = GetActivityPeopleLimit(a.ActivityId, a.Activity.SignUpLimit),
                                 activityState = GetStateDescription(GetActivityState(a.ActivityId)),
                                 postsCount = GetAcitivityPostsCount(a.ActivityId),
                                 founder = GetActivityOrganizer(a.ActivityId),
                                 founderUrl = ApiHelper.Instance.GetUserHomepageLink(GetActivityOrganizerId(a.ActivityId)),
                                 currentClub = a.Activity.Club.ClubName,
                                 friendName = a.User.FullName,
                                 clubUrl = GetClubUrl(a.Activity.ClubId)
                             };
            return activities;
        }

        /// <summary>
        /// 获取用户的活动
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public object GetUserActivites(string userID)
        {
            var activities = from a in _dataContext.ActivitiesMembers
                             where a.UserId == userID orderby a.Activity.BeginDateTime descending
                             select new
                             {
                                 activityId = a.ActivityId,
                                 activityName = a.Activity.ActivityName,
                                 activityUrl = GetAcitivityUrl(a.ActivityId),
                                 activityDate = GetShortDate(a.Activity.BeginDateTime),
                                 beginDateTime = GetLongDateTime(a.Activity.BeginDateTime),
                                 signUpLimit = GetActivityPeopleLimit(a.ActivityId, a.Activity.SignUpLimit),
                                 activityState = GetStateDescription(GetActivityState(a.ActivityId)),
                                 postsCount = GetAcitivityPostsCount(a.ActivityId),
                                 founder = GetActivityOrganizer(a.ActivityId),
                                 founderUrl = ApiHelper.Instance.GetUserHomepageLink(GetActivityOrganizerId(a.ActivityId)),
                                 currentClub = a.Activity.Club.ClubName,
                                 friendName = a.User.FullName,
                                 clubUrl = GetClubUrl(a.Activity.ClubId)
                             };
            return activities;
        }

        /// <summary>
        /// 判断是否活动报名人数已达上限
        /// </summary>
        /// <param name="activityId"></param>
        /// <returns></returns>
        public bool IsActivitySignUpNumExceeded(int activityId)
        {
            IEnumerable<Activity> activities = from a in _dataContext.Activities
                                               where a.ActivityId == activityId && GetJoinedUserNum(activityId) > a.SignUpLimit
                                               select a;
            Activity activity = activities.SingleOrDefault();
            return (activity != null) ? true : false;
        }

        /// <summary>
        /// 判断活动是否已经结束报名
        /// </summary>
        /// <param name="activityId"></param>
        /// <returns></returns>
        public bool IsActivitySignUpFinished(int activityId)
        {
            IEnumerable<Activity> activities = from a in _dataContext.Activities
                                               where a.ActivityId == activityId && DateTime.Now <= a.JoinDeadLine
                                               select a;
            Activity activity = activities.SingleOrDefault();
            return (activity != null) ? false : true;
        }

        /// <summary>
        /// 判断活动是否存在
        /// </summary>
        /// <param name="activityID"></param>
        /// <returns></returns>
        public bool IsActivityExisted(int activityID)
        {
            IEnumerable<Activity> activities = from a in _dataContext.Activities
                                               where a.ActivityId == activityID
                                               select a;
            if (activities.Count() > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 获得活动描述
        /// </summary>
        /// <param name="activityID"></param>
        /// <returns></returns>
        public string GetActivityDescription(int activityID)
        {
            IEnumerable<Activity> activities = from a in _dataContext.Activities
                                               where a.ActivityId == activityID
                                               select a;
            Activity activity = activities.SingleOrDefault();
            if (activity != null)
            {
                return activity.Description;
            }
            return "";

        }

        /// <summary>
        /// 获得活动组织者名称
        /// </summary>
        /// <param name="activityID"></param>
        /// <returns></returns>
        public string GetActivityOrganizer(int activityID)
        {
            IEnumerable<ActivitiesMember> ams = from m in _dataContext.ActivitiesMembers
                                                where m.ActivityId == activityID && m.ActivitiesMemberType == "promoter"
                                                select m;
            ActivitiesMember am = ams.SingleOrDefault();
            if (am != null)
            {
                return am.User.FullName;
            }
            return "";
        }

        /// <summary>
        /// 获取活动组织者Id
        /// </summary>
        /// <param name="activityID"></param>
        /// <returns></returns>
        public string GetActivityOrganizerId(int activityID)
        {
            IEnumerable<ActivitiesMember> ams = from m in _dataContext.ActivitiesMembers
                                                where m.ActivityId == activityID && m.ActivitiesMemberType == "promoter"
                                                select m;
            ActivitiesMember am = ams.SingleOrDefault();
            if (am != null)
            {
                return am.User.UserId;
            }
            return string.Empty;
        }

        /// <summary>
        /// 获得用户活动状态
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="activityId"></param>
        /// <returns></returns>
        public string GetUserActivityState(string userId, int activityId)
        {
            IEnumerable<ActivitiesMember> ams = from m in _dataContext.ActivitiesMembers
                                                where m.UserId == userId && m.ActivityId == activityId
                                                select m;
            ActivitiesMember am = ams.SingleOrDefault();
            if (am != null)
                return am.ActivitiesMemberType;
            return "";
        }

        /// <summary>
        /// 获得加入活动的用户数量
        /// </summary>
        /// <param name="activityID"></param>
        /// <returns></returns>
        public int GetJoinedUserNum(int activityID)
        {
            IEnumerable<ActivitiesMember> ams = from c in _dataContext.ActivitiesMembers
                                                where c.ActivityId == activityID && c.ActivitiesMemberType == "joined"
                                                select c;
            int count = 0;
            foreach (ActivitiesMember am in ams)
            {
                count += am.SingleUserSignUpFemaleNum;
                count += am.SingleUserSignUpMaleNum;
            }

            return ++count;
        }

        /// <summary>
        /// 获得活动信息
        /// </summary>
        /// <param name="activityID"></param>
        /// <returns></returns>
        public Activity GetActivityInfo(int activityID)
        {
            IEnumerable<Activity> activities = from a in _dataContext.Activities
                                               where a.ActivityId == activityID
                                               select a;
            Activity activity = activities.SingleOrDefault();
            if (activity != null)
            {
                return activity;
            }
            return null;
        }

        /// <summary>
        /// 获得好友活动
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public object GetFriendsActivities(string userID)
        {
            var activities = from friend in _dataContext.Friends
                             where friend.UserId == userID && friend.IsAccepted == true
                             join a in _dataContext.ActivitiesMembers on friend.FriendId equals a.UserId orderby a.Activity.BeginDateTime descending
                             select new
                             {
                                 activityId = a.ActivityId,
                                 activityName = a.Activity.ActivityName,
                                 activityUrl = GetAcitivityUrl(a.ActivityId),
                                 activityDate = GetShortDate(a.Activity.BeginDateTime),
                                 beginDateTime = GetLongDateTime(a.Activity.BeginDateTime),
                                 signUpLimit = GetActivityPeopleLimit(a.ActivityId, a.Activity.SignUpLimit),
                                 activityState = GetStateDescription(GetActivityState(a.ActivityId)),
                                 postsCount = GetAcitivityPostsCount(a.ActivityId),
                                 founder = GetActivityOrganizer(a.ActivityId),
                                 founderUrl = ApiHelper.Instance.GetUserHomepageLink(GetActivityOrganizerId(a.ActivityId)),
                                 currentClub = a.Activity.Club.ClubName,
                                 friendName = a.User.FullName,
                                 clubUrl = GetClubUrl(a.Activity.ClubId)
                             };
            return activities;
        }

        /// <summary>
        /// 获取活动状态
        /// </summary>
        /// <param name="activityID"></param>
        /// <returns></returns>
        public int GetActivityState(int activityID)
        {
            IEnumerable<Activity> activities = from a in _dataContext.Activities
                                               where a.ActivityId == activityID
                                               select a;
            Activity activity = activities.SingleOrDefault();
            if (activity == null)
                return -1;
            UpdateActivityStateAutomatic(ref activity);
            return activity.State;
        }

        /// <summary>
        /// 更新活动状态
        /// </summary>
        /// <param name="activityID"></param>
        /// <param name="state"></param>
        public void UpdateActivityState(int activityID, int state)
        {
            if (state > 5 || state < 0)
                return;
            IEnumerable<Activity> activities = from a in _dataContext.Activities
                                               where a.ActivityId == activityID
                                               select a;
            Activity activity = activities.SingleOrDefault();
            if (activity != null)
            {
                activity.State = state;
                _dataContext.SubmitChanges();
            }
        }

        /// <summary>
        /// 新建活动
        /// </summary>
        /// <param name="activityName"></param>
        /// <param name="beginDateTime"></param>
        /// <param name="endDateTime"></param>
        /// <param name="description"></param>
        /// <param name="activityType"></param>
        /// <param name="subject"></param>
        /// <param name="targetAudience"></param>
        /// <param name="joinDeadLine"></param>
        /// <param name="address"></param>
        /// <param name="expense"></param>
        /// <param name="signUpLimit"></param>
        /// <param name="phone"></param>
        /// <param name="email"></param>
        /// <param name="msn"></param>
        /// <param name="qq"></param>
        /// <param name="clubID"></param>
        /// <param name="cityID"></param>
        /// <param name="state"></param>
        /// <param name="isNeedPermission"></param>
        /// <param name="isPublic"></param>
        /// <param name="singleUserSignUpLimit"></param>
        /// <returns></returns>
        public int InsertActivity(
            string activityName,
            DateTime beginDateTime,
            DateTime endDateTime,
            string description,
            int activityType,
            string subject,
            string targetAudience,
            DateTime joinDeadLine,
            string address,
            string expense,
            int signUpLimit,
            string phone,
            string email,
            string msn,
            int qq,
            int clubID,
            int cityID,
            int state,
            bool isNeedPermission,
            bool isPublic,
            int singleUserSignUpLimit)
        {
            Activity activity = new Activity
            {
                ActivityName = activityName,
                BeginDateTime = beginDateTime,
                EndDateTime = endDateTime,
                Description = description,
                ActivityType = activityType,
                Subject = subject,
                TargetAudience = targetAudience,
                JoinDeadLine = joinDeadLine,
                Address = address,
                Expense = expense,
                SignUpLimit = signUpLimit,
                Phone = phone,
                Email = email,
                MSN = msn,
                QQ = qq,
                ClubId = clubID,
                CityId = cityID,
                State = state,
                IsNeedPermission = isNeedPermission,
                IsPublic = isPublic,
                SingleUserSignUpLimit = singleUserSignUpLimit
            };
            _dataContext.Activities.InsertOnSubmit(activity);
            _dataContext.SubmitChanges();
            //FIX ME:当数据库方法提出时，应由以下方法访问数据库方法
            AddActivityAddTrack(activity.ActivityId, activityName);

            _dataContext.SubmitChanges();
            return activity.ActivityId;
        }

        /// <summary>
        /// 更新活动信息
        /// </summary>
        /// <param name="activityID"></param>
        /// <param name="activityName"></param>
        /// <param name="beginDateTime"></param>
        /// <param name="endDateTime"></param>
        /// <param name="description"></param>
        /// <param name="activityType"></param>
        /// <param name="subject"></param>
        /// <param name="targetAudience"></param>
        /// <param name="joinDeadLine"></param>
        /// <param name="address"></param>
        /// <param name="expense"></param>
        /// <param name="signUpLimit"></param>
        /// <param name="phone"></param>
        /// <param name="email"></param>
        /// <param name="msn"></param>
        /// <param name="qq"></param>
        /// <param name="clubID"></param>
        /// <param name="cityID"></param>
        /// <param name="state"></param>
        /// <param name="isNeedPermission"></param>
        /// <param name="isPublic"></param>
        /// <param name="singleUserSignUpLimit"></param>
        public void UpdateActivity(
            int activityID,
            string activityName,
            DateTime beginDateTime,
            DateTime endDateTime,
            string description,
            int activityType,
            string subject,
            string targetAudience,
            DateTime joinDeadLine,
            string address,
            string expense,
            int signUpLimit,
            string phone,
            string email,
            string msn,
            int qq,
            int clubID,
            int cityID,
            int state,
            bool isNeedPermission,
            bool isPublic,
            int singleUserSignUpLimit)
        {
            IEnumerable<Activity> activities = from a in _dataContext.Activities
                                               where a.ActivityId == activityID
                                               select a;
            Activity activity = activities.SingleOrDefault();
            activity.ActivityName = activityName;
            activity.BeginDateTime = beginDateTime;
            activity.EndDateTime = endDateTime;
            activity.Description = description;
            activity.ActivityType = activityType;
            activity.Subject = subject;
            activity.TargetAudience = targetAudience;
            activity.JoinDeadLine = joinDeadLine;
            activity.Address = address;
            activity.Expense = expense;
            activity.SignUpLimit = signUpLimit;
            activity.Phone = phone;
            activity.Email = email;
            activity.MSN = msn;
            activity.QQ = qq;
            activity.ClubId = clubID;
            activity.CityId = cityID;
            activity.State = state;
            activity.IsNeedPermission = isNeedPermission;
            activity.IsPublic = isPublic;
            activity.SingleUserSignUpLimit = singleUserSignUpLimit;
            _dataContext.SubmitChanges();
        }

        /// <summary>
        /// 取得俱乐部最新活动的方法
        /// </summary>
        /// <param name="clubId"></param>
        /// <returns></returns>
        public object GetClubActivity(int clubId)
        {

            var activities = from a in _dataContext.Activities
                             where a.ClubId == clubId
                             select new
                             {
                                 activityId = a.ActivityId,
                                 activityName = a.ActivityName,
                                 activityUrl = GetAcitivityUrl(a.ActivityId),
                                 activityDate = GetShortDate(a.BeginDateTime),
                                 beginDateTime = GetLongDateTime(a.BeginDateTime),
                                 signUpLimit = GetActivityPeopleLimit(a.ActivityId, a.SignUpLimit),
                                 activityState = GetStateDescription(GetActivityState(a.ActivityId)),
                                 postsCount = GetAcitivityPostsCount(a.ActivityId),
                                 founder = GetActivityOrganizer(a.ActivityId),
                                 founderUrl = ApiHelper.Instance.GetUserHomepageLink(GetActivityOrganizerId(a.ActivityId)),
                                 currentClub = a.Club.ClubName,
                                 clubUrl = GetClubUrl(a.Club.ClubId)
                             };
            if (activities.Count() > 0)
            {
                return activities.Take(20);
            }
            else
            {
                return null;
            }

        }

        private string GetShortDate(DateTime dt)
        {
            return dt.ToString("MM-dd");
        }

        private string GetLongDateTime(DateTime dt)
        {
            return dt.ToString("MM-dd HH:mm");
        }
        private string GetClubUrl(int clubId)
        {
            return "/club/default.aspx?activityId=" + clubId.ToString();
        }

        private string GetAcitivityUrl(int activityId)
        {
            return "/activity/detail.aspx?activityId=" + activityId.ToString();
        }
        public int GetClubPagingActivityCount(int clubId)
        {
            var activities = from a in _dataContext.Activities
                             where a.ClubId == clubId
                             select a;
            return activities.Count();
        }
        /// <summary>
        /// 取得俱乐部活动的方法（分页）
        /// </summary>
        /// <param name="clubId"></param>
        /// <returns></returns>
        public object GetClubPagingActivity(int clubId, int beginId, int pageSize)
        {

            var activities = from a in _dataContext.Activities
                             where a.ClubId == clubId
                             select new
                             {
                                 activityId = a.ActivityId,
                                 activityName = a.ActivityName,
                                 activityUrl = GetAcitivityUrl(a.ActivityId),
                                 activityDate = GetShortDate(a.BeginDateTime),
                                 beginDateTime = GetLongDateTime(a.BeginDateTime),
                                 signUpLimit = GetActivityPeopleLimit(a.ActivityId, a.SignUpLimit),
                                 activityState = GetStateDescription(GetActivityState(a.ActivityId)),
                                 postsCount = GetAcitivityPostsCount(a.ActivityId),
                                 founder = GetActivityOrganizer(a.ActivityId),
                                 founderUrl = ApiHelper.Instance.GetUserHomepageLink(GetActivityOrganizerId(a.ActivityId)),
                                 currentClub = a.Club.ClubName,
                                 clubUrl = GetClubUrl(a.Club.ClubId)
                             };
            if (activities.Count() > 0)
            {
                return activities.Skip(beginId).Take(pageSize);
            }
            else
            {
                return null;
            }
        }

        private string GetAcitivityPostsCount(int activityId)
        {
            var pct = from ap in _dataContext.Posts
                      where ap.ObjectId == activityId && ap.ObjectType == 0
                      select ap;
            return pct.Count().ToString();
        }

        /// <summary>
        /// 取得人数限制的方法
        /// </summary>
        /// <param name="applicationId"></param>
        /// <returns></returns>
        public string GetActivityPeopleLimit(int activityId, int signUpLimit)
        {
            string limit;
            int ac = GetJoinedUserNum(activityId);
            limit = ac.ToString() + "/" + signUpLimit.ToString();
            return limit;
        }
        /// <summary>
        /// 取得俱乐部活动分页的方法
        /// </summary>
        /// <param name="clubId"></param>
        /// <returns></returns>
        public IEnumerable<Activity> GetCurrentUserClubPagingActivity(int pageNum)
        {
            int pagesize = 20;
            int clubId;
            var cId = from cu in _dataContext.ClubMembers
                      where cu.UserId == UserRules.Instance.GetCurrentUserId()
                      select cu.Club;
            clubId = Convert.ToInt32(cId);
            IEnumerable<Activity> activities = from a in _dataContext.Activities
                                               where a.ClubId == clubId
                                               select a;
            return activities.Skip(pageNum * pagesize).Take(pagesize).ToList<Activity>();
        }

        /// <summary>
        /// 判断用户是否参加了活动
        /// </summary>
        /// <param name="activityId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool IsUserJoinedActivity(int activityId, string userId)
        {
            IEnumerable<ActivitiesMember> activitiesmembers = from am in _dataContext.ActivitiesMembers
                                                              where am.UserId == userId && am.ActivityId == activityId && am.ActivitiesMemberType != "candidate"
                                                              select am;
            if (activitiesmembers.Count() > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 是否已报名了活动
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public bool IsSignedActivity(string userId, int activityId)
        {
            IEnumerable<ActivitiesMember> activitiesmembers = from am in _dataContext.ActivitiesMembers
                                                              where am.UserId == userId && am.ActivityId == activityId
                                                              select am;
            if (activitiesmembers.Count() > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 向活动添加新的留言主题
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="content"></param>
        public void SendMessage(string userId, string content, int activityid)
        {
            Post post = new Post
            {
                UserId = userId,
                Content = content,
                CreateDateTime = DateTime.Now,
                IsTop = false,
                ObjectType = 1,
                ObjectId = activityid
            };
            _dataContext.Posts.InsertOnSubmit(post);
            _dataContext.SubmitChanges();
            post.ParentId = post.PostId;
            _dataContext.SubmitChanges();
        }

        /// <summary>
        /// 向活动的某条留言添加回复
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="content"></param>
        /// <param name="activityid"></param>
        /// <param name="parentId"></param>
        public void ReplyMessage(string userId, string content, int activityid, int parentId)
        {
            Post post = new Post
            {
                UserId = userId,
                ParentId = parentId,
                Content = content,
                CreateDateTime = DateTime.Now,
                IsTop = false,
                ObjectType = 1,
                ObjectId = activityid
            };
            _dataContext.Posts.InsertOnSubmit(post);
            _dataContext.SubmitChanges();
        }

        /// <summary>
        ///  选出所有活动的留言主题
        /// </summary>
        /// <param name="activityid"></param>
        /// <returns></returns>
        public IEnumerable<Post> GetActivityTopicMessage(int activityid, int beginId, int pageSize)
        {
            IEnumerable<Post> posts = (from p in _dataContext.Posts
                                       where p.PostId == p.ParentId && p.ObjectType == 1 && p.ObjectId == activityid
                                       orderby p.CreateDateTime descending
                                       select p).Skip(beginId).Take(pageSize);
            return posts;
        }

        /// <summary>
        ///  选出所有活动的留言主题总数
        /// </summary>
        /// <param name="activityid"></param>
        /// <returns></returns>
        public int GetActivityTopicMessageCount(int activityid)
        {
            IEnumerable<Post> posts = from p in _dataContext.Posts
                                      where p.PostId == p.ParentId && p.ObjectType == 1 && p.ObjectId == activityid
                                      orderby p.CreateDateTime descending
                                      select p;
            return posts.Count();
        }

        /// <summary>
        ///  选出所有活动的留言主题最新的10条
        /// </summary>
        /// <param name="activityid"></param>
        /// <returns></returns>
        public IEnumerable<Post> GetActivityTopicMessageFor10(int activityid)
        {
            IEnumerable<Post> posts = (from p in _dataContext.Posts
                                       where p.PostId == p.ParentId && p.ObjectType == 1 && p.ObjectId == activityid
                                       orderby p.CreateDateTime descending
                                       select p).Take(10);
            return posts;
        }

        /// <summary>
        /// 取出活动留言的所有回复By活动ID
        /// </summary>
        /// <param name="activityid"></param>
        /// <param name="parentid"></param>
        /// <returns></returns>
        public IEnumerable<Post> GetActivityReplyMessageByParentId(int activityid, int parentid)
        {
            IEnumerable<Post> posts = from p in _dataContext.Posts
                                      where p.ParentId == parentid && p.ObjectType == 1 && p.ObjectId == activityid & p.PostId != p.ParentId
                                      orderby p.CreateDateTime ascending
                                      select p;
            return posts;
        }

        /// <summary>
        /// 删除活动的某条留言及其所有回复
        /// </summary>
        /// <param name="activityid"></param>
        /// <param name="parentid"></param>
        public void DeleteActivityTopicMessageAndReplys(int activityid, int parentid)
        {
            IEnumerable<Post> posts = from p in _dataContext.Posts
                                      where p.ParentId == parentid && p.ObjectType == 1 && p.ObjectId == activityid
                                      select p;
            foreach (var post in posts)
            {
                _dataContext.Posts.DeleteOnSubmit(post);
            }
            _dataContext.SubmitChanges();
        }

        public string GetStateDescription(int stateNum)
        {
            string stateDescript = "";
            switch (stateNum)
            {
                case 0:
                    stateDescript = "报名中";
                    break;
                case 1:
                    stateDescript = "进行中";
                    break;
                case 2:
                    stateDescript = "已结束报名";
                    break;
                case 3:
                    stateDescript = "报名人数已满";
                    break;
                case 4:
                    stateDescript = "填写反馈";
                    break;
                case 5:
                    stateDescript = "已结束";
                    break;
            }
            return stateDescript;
        }

        /// <summary>
        /// 调用GetActivityState时调用并根据数据库记录自动更改活动状态
        /// </summary>
        /// <param name="activity"></param>
        private void UpdateActivityStateAutomatic(ref Activity activity)
        {
            if (activity.State != 5)
            {
                if (IsActivitySignUpNumExceeded(activity.ActivityId))
                {
                    activity.State = 3;
                }
                else if (IsActivitySignUpFinished(activity.ActivityId))
                {
                    activity.State = 2;
                }
                if (DateTime.Now >= activity.BeginDateTime && DateTime.Now <= activity.EndDateTime)
                {
                    activity.State = 1;
                }
                else if (DateTime.Now > activity.EndDateTime)
                {
                    activity.State = 4;
                }
                _dataContext.SubmitChanges();
            }
        }

        private List<string> GetCustomFeedBackQuestionList(string questions)
        {
            if (questions == null)
                return null;
            List<string> questionList = new List<string>();
            string[] seperator = { "#####" };
            string[] questionStings = questions.Split(seperator, StringSplitOptions.RemoveEmptyEntries);
            questionList.AddRange(questionStings);
            return questionList;
        }

        private Dictionary<string, List<string>> GetCustomFeedBackAnswerList(Dictionary<string, string> answer)
        {
            Dictionary<string, List<string>> result = new Dictionary<string, List<string>>();
            foreach (KeyValuePair<string, string> pair in answer)
            {
                List<string> answerList = new List<string>();
                string[] seperator = { "#####" };
                string[] questionStings = pair.Value.Split(seperator, StringSplitOptions.None);
                answerList.AddRange(questionStings);
                result.Add(pair.Key, answerList);
            }
            return result;
        }

        private static ActivityRules _instance;
        private FrienDevDataContext _dataContext = FrienDevDataContext.Instance;
    }


}
